<template>
  <div class="login">
    <div class="login-content">
      <div class="login-form">
        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules">
          <div class="form-title">
            <h2>{{ t("login.title") }}</h2>
          </div>
          <el-form-item prop="userEmail">
            <div class="input-wrapper">
              <el-icon class="mx-2">
                <Message />
              </el-icon>
              <el-input
                ref="userEmail"
                v-model="loginData.userEmail"
                :placeholder="$t('login.username')"
                name="userEmail"
                size="large"
                class="h-[48px]"
                @blur="getRoleList"
              />
            </div>
          </el-form-item>

          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="userPassword">
              <div class="input-wrapper">
                <el-icon class="mx-2">
                  <Lock />
                </el-icon>
                <el-input
                  v-model="loginData.userPassword"
                  :placeholder="$t('login.password')"
                  type="password"
                  name="userPassword"
                  size="large"
                  class="h-[48px] pr-2"
                  show-password
                  @keyup="checkCapslock"
                  @keyup.enter="handleLoginSubmit"
                />
              </div>
            </el-form-item>
          </el-tooltip>
          <el-form-item v-if="showRoles" prop="userId">
            <div class="input-wrapper">
              <el-icon class="mx-2"><Avatar /></el-icon>
              <el-select
                v-model="loginData.userId"
                size="large"
                class="h-[43px]"
                :placeholder="$t('common.plsChoose') + $t('role.name')"
                :no-match-text="$t('common.plsChoose') + $t('role.name')"
              >
                <el-option
                  v-for="[key, label] in Array.from(loginRoles)"
                  :key="key"
                  :label="label"
                  :value="key"
                />
              </el-select>
            </div>
          </el-form-item>
          <div class="flex-x-between w-full py-1">
            <el-checkbox v-model="remenberMe">
              {{ $t("login.rememberMe") }}
            </el-checkbox>
            <router-link type="primary" :to="{ name: 'ForgotPassword' }">
              <el-link type="primary">
                {{ $t("login.forgetPassword") }}
              </el-link>
            </router-link>
          </div>

          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="w-full"
            @click.prevent="handleLoginSubmit"
          >
            {{ $t("login.login") }}
          </el-button>
          <router-link type="primary" :to="{ name: 'CustomerRegister' }">
            <p style="text-align: center">
              <el-text>{{ t("login.noAccount") }}</el-text>
              <el-link style="padding-left: 5px" type="primary">
                {{ t("login.registerNow") }}
              </el-link>
            </p>
          </router-link>
        </el-form>
      </div>
    </div>

    <div class="login-footer">
      <el-text size="small">Copyright © {{ nowYear }} All Rights Reserved.</el-text>
    </div>
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";

import { type LoginData } from "@/api/auth";
import router from "@/router";

import type { FormInstance } from "element-plus";

import { useSettingsStore, useUserStore } from "@/store";
import UserAPI from "@/api/system/user";

import dayjs from "dayjs";

const userStore = useUserStore();

const nowYear = ref(dayjs().year());

const route = useRoute();
const { t } = useI18n();
const loginFormRef = ref<FormInstance>();

const loading = ref(false);
const isCapslock = ref(false);

const remenberMe = ref(false);
const loginRoles = ref<Map<string, string>>(new Map());
const showRoles = ref(false);

const loginImage = ref(new URL("../../assets/images/login-image.svg", import.meta.url).href);

const loginData = ref<LoginData>({
  userEmail: "",
  userPassword: "",
  userId: undefined,
});

const loginRules = computed(() => {
  return {
    userEmail: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    userPassword: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
  };
});

async function handleLoginSubmit() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      localStorage.removeItem("regionId");
      localStorage.removeItem("regionName");
      if (remenberMe.value) {
        localStorage.setItem("remenberMe", "true");
        localStorage.setItem("email", loginData.value.userEmail);
        localStorage.setItem("passoword", loginData.value.userPassword);
        if (loginData.value.userId != undefined) {
          localStorage.setItem("roleUserId", loginData.value.userId.toString());
        }
      } else {
        localStorage.removeItem("email");
        localStorage.removeItem("passoword");
        localStorage.setItem("remenberMe", "false");
      }

      loading.value = true;
      userStore
        .login(loginData.value)
        .then(async () => {
          ElMessage.success(t("login.success"));
          await userStore.getUserInfo();
          const { path, queryParams } = parseRedirect();
          router.push({ path: path, query: queryParams });
          router.push("/");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * parse redirect string to path and  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } parsed path and queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

function checkCapslock(event: KeyboardEvent) {
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

function getRoleList() {
  if (!loginData.value.userEmail) return;
  loginData.value.userId = undefined;
  UserAPI.getUserRolesByEmail(loginData.value.userEmail)
    .then((res) => {
      if (res.status === undefined) {
        console.log(res);
        loginRoles.value = new Map(Object.entries(res));
        //loginRoles.value = res;
        console.log(loginRoles.value);
        showRoles.value = true;
        const roleUserId = localStorage.getItem("roleUserId");
        if (roleUserId != null) {
          const _roleUserId = Number(roleUserId);
          if (loginRoles.value?.get(roleUserId)) {
            loginData.value.userId = roleUserId;
          }
        }
      } else {
        showRoles.value = false;
      }
    })
    .catch((err) => {
      console.log(err);
    });
}

onMounted(() => {
  if (localStorage.getItem("remenberMe") === "true") {
    remenberMe.value = true;
    loginData.value.userEmail = localStorage.getItem("email") ?? "";
    loginData.value.userPassword = localStorage.getItem("passoword") ?? "";
  }
  getRoleList();
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: url("@/assets/images/login-background-light.jpg") no-repeat center right;

  .login-header {
    position: absolute;
    top: 0;
    display: flex;
    justify-content: right;
    width: 100%;
    padding: 15px;

    .logo {
      width: 26px;
      height: 26px;
    }

    .title {
      margin: auto 5px;
      font-size: 24px;
      font-weight: bold;
      color: #3b82f6;
    }
  }

  .login-content {
    display: flex;
    width: 450px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);

    @media (width <= 768px) {
      flex-direction: column;
      max-width: 100%;
      height: 100vh;
      padding: 0 30px;
      border-radius: 0;
      box-shadow: none;
    }

    .login-img {
      display: flex;
      flex: 3;
      align-items: center;
      justify-content: center;
      background: linear-gradient(60deg, #165dff, #6aa1ff);

      @media (width <= 768px) {
        display: none;
      }
    }

    .login-form {
      display: flex;
      flex: 2;
      flex-direction: column;
      justify-content: center;
      padding: 30px;

      @media (width <= 768px) {
        width: 100%;
        padding: 0 20px;
      }

      .form-title {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 0 20px;
        text-align: center;
      }

      .input-wrapper {
        display: flex;
        align-items: center;
        width: 100%;
      }

      .captcha-img {
        height: 48px;
        cursor: pointer;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
      }

      .third-party-login {
        display: flex;
        justify-content: center;
        width: 100%;
        color: var(--el-text-color-secondary);

        *:not(:first-child) {
          margin-left: 20px;
        }

        .icon {
          cursor: pointer;
        }
      }
    }
  }

  .login-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

:deep(.el-form-item) {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
:deep(.el-select) {
  .el-select__wrapper {
    box-shadow: none !important;
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-background-dark.jpg") no-repeat center right;

    .login-content {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
</style>
